package com.learn.basic.proxy;

import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.UUID;
@Slf4j
public class TestProxyClazz {
    //
    interface TestInterface {
        String test01();
        String test02(String st, String st2);
    }
    //
    class TestProxy implements InvocationHandler {
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            switch (method.getName()) {
                case "test01":
                    return "invoke-test01-" + UUID.randomUUID().toString();
                case "test02":
                    return "invoke-test02-" + Arrays.asList(args);
                default:
                    return null;
            }
        }
    }
    //
    class TestFactory{
        public <T> T newInstance(Class<T> clazz){
            InvocationHandler handler = new TestProxy();
            return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, handler);
        }
    }

    public static void main(String[] args) {
        TestProxyClazz testProxyClazz = new TestProxyClazz();
        TestFactory factory = testProxyClazz.new TestFactory();
        TestInterface testInterface = factory.newInstance(TestInterface.class);
        log.info("{}", testInterface.test01());
        log.info("{}", testInterface.test02("a", "b"));
    }
}
